import { createRouter } from 'vue-router'
import { createWebHashHistory } from 'vue-router'

import BaseLayout from '@/layout/BaseLayout'
import SpaceLayout from '@/layout/SpaceLayout'

import api from '@/odoojs/index.js'
// console.log('router', api, api.lang)
// api.lang = 'en_US'

const userRoutes = [
  {
    path: '/user',
    component: SpaceLayout,
    children: [
      {
        path: '/web/login',
        component: () => import('@/views/user/LoginPage'),
        name: 'web-login'
      }
    ]
  }
]

const homeRoutes = [
  {
    path: '/',
    component: BaseLayout,
    redirect: '/home',

    children: [
      {
        path: '/home',
        component: () => import('@/views/home/HomePage'),
        name: 'home'
      },
      {
        path: '/antv_s2_sale',
        component: () => import('@/views/antvs2/SaleLine'),
        name: 'antv_s2_sale'
      },

      {
        path: '/web',
        component: () => import('@/views/web/WebPage'),
        name: 'error'
      }
    ]
  }
]

const allRoutes = [...userRoutes, ...homeRoutes]

const router = createRouter({
  history: createWebHashHistory(),
  routes: allRoutes
})

router.beforeEach(async (to, from, next) => {
  // console.log(to, from)

  const whiteList = ['/web/login']

  if (whiteList.includes(to.path)) {
    next()
    return
  }

  const hasToken = await api.session_check()

  // const locallang = localStorage.getItem('lang') || lang_default
  // if (locallang) {
  //   await api.env.set_lang(locallang)
  // }

  if (hasToken) {
    next()
    return
  } else {
    next(`/web/login`)

    return
  }
})

export default router
